import 'dart:html' as html;
import 'dart:async';

class WebTTSService {
  static final WebTTSService _instance = WebTTSService._internal();
  factory WebTTSService() => _instance;
  WebTTSService._internal();

  html.SpeechSynthesis? _speechSynthesis;
  html.SpeechSynthesisUtterance? _currentUtterance;
  bool _isInitialized = false;
  bool _isSpeaking = false;

  // 语音设置
  double _speechRate = 1.0; // 默认语速
  double _pitch = 1.0; // 音调
  double _volume = 1.0;
  String _voice = '';
  html.SpeechSynthesisVoice? _selectedVoice;

  // 初始化Web TTS
  Future<void> initialize() async {
    if (_isInitialized) return;

    try {
      // 检查浏览器是否支持Web Speech API
      if (html.window.speechSynthesis == null) {
        print('❌ 浏览器不支持Web Speech API');
        return;
      }

      _speechSynthesis = html.window.speechSynthesis;

      // 等待语音列表加载
      await _loadVoices();

      _isInitialized = true;
      print('✅ Web TTS服务初始化成功');

      // 设置事件监听
      _setupEventListeners();
    } catch (e) {
      print('❌ Web TTS服务初始化失败: $e');
    }
  }

  // 加载可用的语音
  Future<void> _loadVoices() async {
    if (_speechSynthesis == null) return;

    try {
      // 获取语音列表
      final voices = _speechSynthesis!.getVoices();
      print('🎤 可用语音数量: ${voices.length}');

      // 查找最佳中文语音（优先选择女声、本地语音）
      html.SpeechSynthesisVoice? bestVoice;
      html.SpeechSynthesisVoice? fallbackVoice;

      for (final voice in voices) {
        final lang = voice.lang?.toLowerCase() ?? '';
        final name = voice.name?.toLowerCase() ?? '';

        if (lang.startsWith('zh')) {
          // 优先选择本地语音
          if (voice.localService == true) {
            // 优先选择女声，通常声音更清晰
            if (name.contains('female') ||
                name.contains('女') ||
                name.contains('xiaoxiao') ||
                name.contains('xiaoyi') ||
                name.contains('tingting') ||
                name.contains('yaoyao') ||
                name.contains('google') && name.contains('zh')) {
              bestVoice = voice;
              break;
            }
            // 其次选择本地语音
            if (bestVoice == null) {
              bestVoice = voice;
            }
          } else if (fallbackVoice == null) {
            // 备选：任何中文语音
            fallbackVoice = voice;
          }
        }
      }

      // 选择最佳语音
      _selectedVoice = bestVoice ?? fallbackVoice;
      if (_selectedVoice != null) {
        _voice = _selectedVoice!.name!;
        final isLocal = _selectedVoice!.localService == true ? '本地' : '在线';
        print('✅ 选择语音: $_voice ($isLocal)');
      } else if (voices.isNotEmpty) {
        _selectedVoice = voices.first;
        _voice = _selectedVoice!.name!;
        print('⚠️ 未找到中文语音，使用默认语音: $_voice');
      }
    } catch (e) {
      print('❌ 加载语音列表失败: $e');
    }
  }

  // 设置事件监听
  void _setupEventListeners() {
    if (_speechSynthesis == null) return;

    // 监听语音列表变化
    _speechSynthesis!.addEventListener('voiceschanged', (event) {
      _loadVoices();
    });
  }

  // 朗读文本
  Future<void> speak(String text) async {
    if (!_isInitialized) {
      await initialize();
    }

    if (_speechSynthesis == null) {
      print('❌ Web TTS未初始化');
      return;
    }

    try {
      print(
        '🎤 Web TTS开始朗读: ${text.length > 50 ? text.substring(0, 50) + '...' : text}',
      );

      // 停止当前播放
      await stop();

      // 创建新的语音合成实例
      _currentUtterance = html.SpeechSynthesisUtterance(text);

      // 设置语音参数
      _currentUtterance!.rate = _speechRate;
      _currentUtterance!.pitch = _pitch;
      _currentUtterance!.volume = _volume;

      // 设置语音
      if (_selectedVoice != null) {
        _currentUtterance!.voice = _selectedVoice;
      } else if (_voice.isNotEmpty) {
        final voices = _speechSynthesis!.getVoices();
        for (final voice in voices) {
          if (voice.name == _voice) {
            _currentUtterance!.voice = voice;
            _selectedVoice = voice; // 缓存选中的语音
            break;
          }
        }
      }

      // 设置事件监听
      _currentUtterance!.addEventListener('start', (event) {
        _isSpeaking = true;
        print('✅ Web TTS朗读开始');
      });

      _currentUtterance!.addEventListener('end', (event) {
        _isSpeaking = false;
        print('✅ Web TTS朗读结束');
      });

      _currentUtterance!.addEventListener('error', (event) {
        _isSpeaking = false;
        print('❌ Web TTS朗读错误');
      });

      // 开始朗读
      _speechSynthesis!.speak(_currentUtterance!);
    } catch (e) {
      print('❌ Web TTS朗读失败: $e');
    }
  }

  // 停止朗读
  Future<void> stop() async {
    if (_speechSynthesis == null) return;

    try {
      _speechSynthesis!.cancel();
      _isSpeaking = false;
      _currentUtterance = null;
      print('⏹️ Web TTS朗读已停止');
    } catch (e) {
      print('❌ Web TTS停止朗读失败: $e');
    }
  }

  // 暂停朗读
  Future<void> pause() async {
    if (_speechSynthesis == null) return;

    try {
      _speechSynthesis!.pause();
      print('⏸️ Web TTS朗读已暂停');
    } catch (e) {
      print('❌ Web TTS暂停朗读失败: $e');
    }
  }

  // 恢复朗读
  Future<void> resume() async {
    if (_speechSynthesis == null) return;

    try {
      _speechSynthesis!.resume();
      print('▶️ Web TTS朗读已恢复');
    } catch (e) {
      print('❌ Web TTS恢复朗读失败: $e');
    }
  }

  // 检查是否正在朗读
  bool get isSpeaking => _isSpeaking;

  // 设置语音速率
  void setSpeechRate(double rate) {
    _speechRate = rate.clamp(0.1, 1.0);
    print('🎚️ Web TTS语音速率设置为: $_speechRate');
  }

  // 设置音调
  void setPitch(double pitch) {
    _pitch = pitch.clamp(0.0, 2.0);
    print('🎵 Web TTS音调设置为: $_pitch');
  }

  // 设置音量
  void setVolume(double volume) {
    _volume = volume.clamp(0.0, 1.0);
    print('🔊 Web TTS音量设置为: $_volume');
  }

  // 设置语音
  void setVoice(String voiceName) {
    if (_speechSynthesis == null) return;

    final voices = _speechSynthesis!.getVoices();
    for (final voice in voices) {
      if (voice.name == voiceName) {
        _selectedVoice = voice;
        _voice = voiceName;
        print('🎭 Web TTS语音设置为: $voiceName');
        break;
      }
    }
  }

  // 获取当前选中的语音
  String get currentVoice => _voice;

  // 获取当前设置
  Map<String, dynamic> getCurrentSettings() {
    return {
      'rate': _speechRate,
      'pitch': _pitch,
      'volume': _volume,
      'voice': _voice,
    };
  }

  // 获取可用语音列表
  List<Map<String, String>> getAvailableVoices() {
    if (_speechSynthesis == null) return [];

    final voices = _speechSynthesis!.getVoices();
    return voices
        .map(
          (voice) => {
            'name': voice.name ?? '',
            'lang': voice.lang ?? '',
            'localService': voice.localService?.toString() ?? 'false',
          },
        )
        .toList();
  }

  // 释放资源
  void dispose() {
    stop();
    _isInitialized = false;
    print('🗑️ Web TTS服务已释放');
  }

  // 检查是否支持
  bool get isSupported {
    return html.window.speechSynthesis != null;
  }
}
